package com.approval.exception;

import com.approval.dto.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.util.stream.Collectors;

/**
 * 全局异常处理器
 * 统一处理所有异常并返回标准格式
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    
    /**
     * 处理业务异常
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<Void> handleBusinessException(BusinessException e, HttpServletRequest request) {
        logger.warn("业务异常: {} - {}", request.getRequestURI(), e.getMessage());
        return Result.error(e.getCode(), e.getMessage());
    }
    
    /**
     * 处理参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<Void> handleValidationException(MethodArgumentNotValidException e) {
        String message = e.getBindingResult().getFieldErrors().stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining("; "));
        logger.warn("参数校验异常: {}", message);
        return Result.error(400, "参数校验失败: " + message);
    }
    
    /**
     * 处理绑定异常
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<Void> handleBindException(BindException e) {
        String message = e.getBindingResult().getFieldErrors().stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining("; "));
        logger.warn("绑定异常: {}", message);
        return Result.error(400, "参数绑定失败: " + message);
    }
    
    /**
     * 处理非法参数异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<Void> handleIllegalArgumentException(IllegalArgumentException e, HttpServletRequest request) {
        logger.warn("非法参数异常: {} - {}", request.getRequestURI(), e.getMessage());
        return Result.error(400, e.getMessage());
    }
    
    /**
     * 处理数据库相关异常
     */
    @ExceptionHandler({SQLException.class, DataAccessException.class})
    @ResponseStatus(HttpStatus.OK)
    public Result<Void> handleDatabaseException(Exception e, HttpServletRequest request) {
        logger.error("数据库异常: {} - {}", request.getRequestURI(), e.getMessage(), e);
        
        String message = "数据库操作失败";
        
        // 检测是否是字段不存在的错误
        if (e.getMessage() != null && e.getMessage().contains("Unknown column")) {
            message = "系统配置错误，请联系管理员更新数据库结构";
        } else if (e.getMessage() != null && e.getMessage().contains("could not extract ResultSet")) {
            message = "数据查询失败，请联系管理员检查数据库配置";
        } else if (isDevelopment()) {
            // 开发环境返回详细信息
            message = "数据库错误: " + e.getMessage();
        }
        
        return Result.error(500, message);
    }
    
    /**
     * 处理空指针异常
     */
    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<Void> handleNullPointerException(NullPointerException e, HttpServletRequest request) {
        logger.error("空指针异常: {} - {}", request.getRequestURI(), e.getMessage(), e);
        return Result.error(500, "系统内部错误，请联系管理员");
    }
    
    /**
     * 处理所有未捕获的异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<Void> handleException(Exception e, HttpServletRequest request) {
        logger.error("未知异常: {} - {}", request.getRequestURI(), e.getMessage(), e);
        
        String message = "系统繁忙，请稍后重试";
        
        // 开发环境返回详细错误信息
        if (isDevelopment()) {
            // 提取最有用的错误信息
            Throwable rootCause = getRootCause(e);
            message = "系统错误: " + (rootCause != null ? rootCause.getMessage() : e.getMessage());
        }
        
        return Result.error(500, message);
    }
    
    /**
     * 获取异常的根本原因
     */
    private Throwable getRootCause(Throwable throwable) {
        Throwable cause = throwable;
        while (cause.getCause() != null && cause.getCause() != cause) {
            cause = cause.getCause();
        }
        return cause;
    }
    
    /**
     * 判断是否为开发环境
     */
    private boolean isDevelopment() {
        // 可以从配置文件或环境变量读取
        return true; // 默认开发环境
    }
}

